/*
 * ExcelExporter.java
 *
 * Created on 17 de agosto de 2007, 03:03 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package ig.formato.util;

import java.awt.Component;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 * @author jsanchez
 */
public class ExcelExporter {

    public ExcelExporter() {
    }

    public static void exportTable(JTable table, Component comp, String nombreHoja) throws IOException {

        javax.swing.JFileChooser sFile = new javax.swing.JFileChooser();
        sFile.setAcceptAllFileFilterUsed(false);
        sFile.setFileFilter(new ig.formato.util.ExampleFileFilter("xls", "Hoja de Calculo"));
        sFile.showSaveDialog(comp);

        File file = null;
        if (sFile.getSelectedFile() != null) {
            if (!sFile.getSelectedFile().getName().toUpperCase().trim().endsWith(".XLS")) {
                file = new File(sFile.getSelectedFile().getAbsolutePath().trim() + ".xls");
            } else {
                file = sFile.getSelectedFile();
            }
            if (file.exists()) {
                if (JOptionPane.showConfirmDialog(comp, "Ya existe un archivo con el mismo nombre, desea remplazarlo ?", "Remplazar", JOptionPane.YES_NO_OPTION) == 1) {
                    return;
                }
            }
        } else {
            return;
        }

        DataOutputStream out = new DataOutputStream(new FileOutputStream(file));

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet s = wb.createSheet();
        wb.setSheetName(0, nombreHoja == null ? "Export" : nombreHoja/*, HSSFWorkbook.ENCODING_UTF_16*/);

        TableModel model = table.getModel();
        HSSFRow r = s.createRow(0);
        Map<Integer,Integer> lenght  = new HashMap<Integer, Integer>();
        int aux = 256;
        int pik = 4;
        for (int i = 0; i < model.getColumnCount(); i++) {
            HSSFCell c = r.createCell( i);
            //c.setEncoding(HSSFCell.ENCODING_UTF_16);
            c.setCellType(HSSFCell.CELL_TYPE_STRING);
            c.setCellValue(model.getColumnName(i).toUpperCase());
            HSSFCellStyle cellStyle = wb.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            c.setCellStyle(cellStyle);

            HSSFFont cellFFont = wb.createFont();
            cellFFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            cellFFont.setFontHeightInPoints((short)9);
            cellStyle.setFont(cellFFont);
            lenght.put(i, ( pik + model.getColumnName(i).toUpperCase().length() ) * aux);
            s.setColumnWidth( i, lenght.get(i).shortValue());
        }

        
        HSSFFont cellFFont = wb.createFont();
        //cellFFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        cellFFont.setFontHeightInPoints((short)9);        
        for (int i = 1; i <= table.getRowCount(); i++) {
            r = s.createRow(i);
            for (int j = 0; j < table.getColumnCount(); j++) {
                Object objeto = table.getValueAt(i - 1, j);
                HSSFCell c = r.createCell(j);
                //c.setEncoding(HSSFCell.ENCODING_UTF_16);

                HSSFCellStyle cellStyle = wb.createCellStyle();
                cellStyle.setFont(cellFFont);

                if (objeto instanceof Date) {
                    c.setCellValue((Date) objeto);
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                } else if (objeto instanceof Integer) {
                    c.setCellValue((Integer) objeto);
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                } else if (objeto instanceof Double) {
                    c.setCellValue((Double) objeto);
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
                }else if (objeto instanceof BigDecimal) {
                    c.setCellValue( new Double(objeto.toString()));
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
                } else if (objeto instanceof String) {
                    c.setCellValue((String) objeto);
                    cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
                }
                if(lenght.get(j)< (objeto.toString().length() + pik) * aux  ){
                    lenght.put(j, (objeto.toString().length() + pik) * aux  );
                    s.setColumnWidth( j, lenght.get(j).shortValue());
                }
                c.setCellStyle(cellStyle);
            }
        }
        wb.write(out);
        out.close();
    }
}
